package pri.hillchen.std.simpledemo.javaapi;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 12:39 2018/3/12 0012.
 */
public class ZookeeperUtil {
    private static final String CONNECTSTRING = "localhost:2181";
    private static final int SESSION_TIMEOUT = 20000;
    public static ZooKeeper createClient() throws IOException, InterruptedException {
        return createClient(CONNECTSTRING,SESSION_TIMEOUT);
    }

    /**
     * 同步创建连接。
     * @param connectString
     * @return
     * @throws IOException
     */
    public static ZooKeeper createClient(String connectString,int sessionTimeOut) throws IOException, InterruptedException {
        ZooKeeper zooKeeper ;
        CountDownLatch latch = new CountDownLatch(1);
        zooKeeper = new ZooKeeper(connectString,SESSION_TIMEOUT,(WatchedEvent watchedEvent) ->{
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                // 放开闸门, wait在connect方法上的线程将被唤醒
                System.out.println("创建连接成功!");
                latch.countDown();
            }
        });
        latch.await();
        return zooKeeper;
    }
}
